package com.gitee.ricesugar.mall.model.DAO;

import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class ConnectionPool {

    private static Connection instance = null;
    private String url = "jdbc:mysql://";
    private String host;
    private String port;
    private String database;
    private String username;
    private String password;

    private ConnectionPool() throws ClassNotFoundException, SQLException {
        readConfig();

        Class.forName("com.mysql.cj.jdbc.Driver");

        instance = DriverManager.getConnection(url, username, password);
    }

    private void readConfig() {
        Properties properties = new Properties();
        try {
            InputStream input = ConnectionPool.class.getClassLoader().getResourceAsStream("config.properties");
//            FileReader reader = new FileReader("config.properties");
            properties.load(input);
            host = properties.getProperty("host");
            port = properties.getProperty("port");
            database = properties.getProperty("database");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
//            reader.close();
            input.close();

            url = url + host + ":" + port + "/" + database;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Connection getInstance() throws SQLException, ClassNotFoundException {
        if (instance == null) {
            new ConnectionPool();
        }
        return instance;
    }
}
